package com.rla.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.rla.common.exception.ServiceException;
import com.rla.common.utils.redis.RedisUtils;
import com.rla.common.wechat.bo.WxBindingPhoneBo;
import com.rla.common.wechat.constant.WeChatConstants;
import com.rla.common.wechat.utils.RestTemplateUtil;
import com.rla.common.wechat.utils.WxUtil;
import com.rla.common.wechat.vo.ProgramTemplateMessageVo;
import com.rla.common.wechat.vo.WeChatAccessTokenVo;
import com.rla.common.wechat.vo.WeChatMiniAuthorizeVo;
import com.rla.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
@Slf4j
@EnableAsync
public class WeChatService {


    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private ISysConfigService configService;

    public static final String WECHAT_MINI_APPID = "routine_appid";
    /**
     * 小程序appSecret key
     */
    public static final String WECHAT_MINI_APPSECRET = "routine_appsecret";

    public String getUserPhone(WxBindingPhoneBo bo) {
        // 1、从配置表总获取小程序的appid和appsecret
        String appId = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPID));
        String secret = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPSECRET));
        String decrypt = WxUtil.decrypt(appId, bo.getEncryptedData(), bo.getSessionKey(), bo.getIv());
        if (StrUtil.isBlank(decrypt)) {
            throw new ServiceException("微信小程序获取手机号解密失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        if (StrUtil.isBlank(jsonObject.getString("phoneNumber"))) {
            throw new ServiceException("微信小程序获取手机号没有有效的手机号");
        }
        return jsonObject.getString("phoneNumber");
    }


    public WeChatMiniAuthorizeVo getAuthorizeVo(String code) {
        // 1、从配置表总获取小程序的appid和appsecret
        String appId = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPID));
        String secret = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPSECRET));
        // 2、根据code/appId/secret请求小程序认证服务
        String url = StrUtil.format(WeChatConstants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new ServiceException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                throw new ServiceException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatMiniAuthorizeVo.class);
    }


    /**
     * 获取小程序accessToken
     *
     * @return accessToken
     */
    public String getMiniAccessToken() {
        boolean exists = RedisUtils.hasKey(WeChatConstants.REDIS_WECAHT_MINI_ACCESS_TOKEN_KEY);
        if (exists) {
            Object accessToken = RedisUtils.getCacheObject(WeChatConstants.REDIS_WECAHT_MINI_ACCESS_TOKEN_KEY);
            return accessToken.toString();
        }
        String appId = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPID));
        String secret = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPSECRET));

        String url = StrUtil.format(WeChatConstants.WECHAT_ACCESS_TOKEN_URL, appId, secret);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new ServiceException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                throw new ServiceException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        WeChatAccessTokenVo accessTokenVo = JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);
        // 缓存accessToken
        RedisUtils.setCacheObject(WeChatConstants.REDIS_WECAHT_MINI_ACCESS_TOKEN_KEY, accessTokenVo.getAccessToken(),
                Duration.ofSeconds(accessTokenVo.getExpiresIn().longValue() - 2800L)
              );
        return accessTokenVo.getAccessToken();
    }



    @Async
    public void sendMiniSubscribeMessage(ProgramTemplateMessageVo templateMessageVo) {
        String accessToken = getMiniAccessToken();
        String url = StrUtil.format(WeChatConstants.WECHAT_MINI_SEND_SUBSCRIBE_URL, accessToken);
        JSONObject messAge = JSONObject.parseObject(JSONObject.toJSONString(templateMessageVo));
        String result = restTemplateUtil.postJsonData(url, messAge);
        JSONObject data = JSONObject.parseObject(result);
        if (ObjectUtil.isNull(data)) {
            log.error("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                log.error("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
    }


    public String getRunNum(WxBindingPhoneBo bo) {
        // 1、从配置表总获取小程序的appid和appsecret
        String appId = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPID));
        String secret = Convert.toStr(configService.selectConfigByKey(WECHAT_MINI_APPSECRET));
        String decrypt = WxUtil.decrypt(appId, bo.getEncryptedData(), bo.getSessionKey(), bo.getIv());
        if (StrUtil.isBlank(decrypt)) {
            throw new ServiceException("微信小程序获取运动步数解密失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        if (StrUtil.isBlank(jsonObject.getString("stepInfoList"))) {
            throw new ServiceException("微信小小程序获取运动步为空");
        }
        return jsonObject.getString("stepInfoList");
    }

//    public String getEssayList(String offset, String count) {
//
//        Map<String, String> map = MapUtil.newHashMap();
//        map.put("type", "news");//素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
//        map.put("offset", offset);//从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
//        map.put("count", count);//返回素材的数量，取值在1到20之间
//        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(map));
//
//        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + redisService.getCacheObject(WeChatConstants.REDIS_WECAHT_PUBLIC_NUMBER_ACCESS_TOKEN_KEY).toString();
//        JSONUtil.parse(map);
//
//        String essays = restTemplateUtil.postJsonData(url, jsonObject);
//        return essays;
//    }

}
